package com.pitaya.framework.common;

import java.io.UnsupportedEncodingException;
import java.util.Random;
import java.util.UUID;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class StringUtils extends org.apache.commons.lang3.StringUtils {
	
	private static final Log log = LogFactory.getLog(StringUtils.class);
	
	public static String substringWithChinese(String content, int length) {
		byte[] bytes;
		try {
			bytes = content.getBytes("Unicode");
		} catch (UnsupportedEncodingException e) {
			log.error(e.getMessage());
			return content;
		}
		int n = 0; // 表示当前的字节数
		int i = 2; // 要截取的字节数，从第3个字节开始
		for (; i < bytes.length && n < length; i++) {
			// 奇数位置，如3、5、7等，为UCS2编码中两个字节的第二个字节
			if (i % 2 == 1) {
				n++; // 在UCS2第二个字节时n加1
			} else {
				// 当UCS2编码的第一个字节不等于0时，该UCS2字符为汉字，一个汉字算两个字节
				if (bytes[i] != 0) {
					n++;
				}
			}
		}
		// 如果i为奇数时，处理成偶数
		/*
		 * if (i % 2 == 1){ // 该UCS2字符是汉字时，去掉这个截一半的汉字 if (bytes[i - 1] != 0) i =
		 * i - 1; // 该UCS2字符是字母或数字，则保留该字符 else i = i + 1; }
		 */
		// 将截一半的汉字要保留
		if (i % 2 == 1) {
			i = i + 1;
		}
		try {
			return new String(bytes, 0, i, "Unicode");
		} catch (UnsupportedEncodingException e) {
			log.error(e.getMessage());
			return content;
		}
	}
	
	public static String getRandomStr(int length) {
	    String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	    Random random = new Random();
	    StringBuffer sb = new StringBuffer();
	    for (int i = 0; i < length; i++) {
	      sb.append(str.charAt(random.nextInt(62)));
	    }
	    return sb.toString();
	}
	
	public static String getUUID() {
	    return UUID.randomUUID().toString().replaceAll("-", "");
	}
	
	public static String getLikePattern(String value) {
		StringBuilder likePatternStr = new StringBuilder();
		return likePatternStr.append("%").append(value).append("%").toString();
	}
}
